package com.bd.rj.common.filters;

import ch.qos.logback.core.spi.FilterReply;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 白世俊
 * @desc 响应跨域请求过滤器
 * @datetime: 2024-12-26 11:00
 */
@WebFilter("/*")
public class CrosFilter implements Filter {
    protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException {

    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("全局过滤器收到请求");
        HttpServletRequest httpreq = (HttpServletRequest) req;
        HttpServletResponse httpresp = (HttpServletResponse) resp;
        //基础resp跨域参数
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        httpresp.setHeader("Access-Control-Allow-Credentials", "true");
        httpresp.setHeader("Access-Control-Allow-Origin", "*");
        httpresp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With,Content-Type,Accept,Cookie,Authorization,token");
        httpresp.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        if ("OPTIONS".equals(httpreq.getMethod())) {
            httpresp.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        filterChain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
